<template>
  <!--  通知通告维护  -->
  <div>
    <!-- 搜索 -->
    <TopFilter
      :list="topFilterInit"
      :cols="3"
      labelWidth="90"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <!-- 按钮 -->

    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :onRowSelectChange="selectChange"
      :onColumnsChange="columns => this.columns = columns"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="detailHandle(null,'add')">新增</el-button>
        <!-- <el-button size="small" type="primary" icon="el-icon-remove-outline" @click="withdraw">撤回</el-button> -->
      </template>
    </FilterTable>

    <!-- 新增窗口 -->
    <Drawer
      :visible.sync="visibleDrawer"
      :title="title"
      :width="920"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
       >
      <info-modal v-if="visibleDrawer" v-model="initData" @close="infoClose" />
    </Drawer>

    <BaseDialog
      :title="readTitle"
      :visible.sync="readShow"
      width="1000px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <read v-if="readTitle == '已读列表'?true:false" :readData="readData"/>
      <noRead v-else :readData="readData"/>
    </BaseDialog>
  </div>
</template>

<script>
import infoModal from './info';
import { pageNotificationMaintaion , withdrawNotificationByIds , deleteNotification,publishNotification} from '@/api/admin/notice/dcsNoticeMaintain/index';
import { dictionary } from '@/utils/dictMixin';
import { parseTime } from '@/utils/index';
import read from './read'
import noRead from './noRead'
import moment from 'moment'
export default {
  mixins: [dictionary],
  components: {
    infoModal,
    read,
    noRead
  },
  data() {
    return {
      topFilterInit: this.topFilterInitFun(),
      columns: this.creatHeader(),
      fetchApi: pageNotificationMaintaion, //api 接口 table请求数据入口
      fetchParams: null,
      visibleDrawer: false,
      initData: {},
      readTitle:"已读列表",
      title:"通知通告新增",
      readShow:false,
      readData:"",
    };
  },
 
  mounted() {
    // this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    topFilterInitFun() {
      return [
        { type: 'SELECT', label: '公告类别', fieldName: 'notificationType', placeholder: '请选择', initialValue: '', itemList: this.createDictList('2561') },
        { type: 'INPUT', label: '标题', fieldName: 'notificationTitle', placeholder: '请输入', initialValue: '' },
        { type: 'INPUT', label: '发布人', fieldName: 'publishPerson', placeholder: '请输入', initialValue: '' },
        { type: 'SELECT', label: '状态', fieldName: 'status', placeholder: '请选择', initialValue: '', itemList: this.createDictList('2563') },
        { type: 'RANGE_DATE', label: '发布时间', fieldName: 'publishDate', valueFormat: 'yyyy-MM-dd', placeholder: '请选择' },
        { type: 'RANGE_DATE', label: '有效期至', fieldName: 'startTime', valueFormat: 'yyyy-MM-dd', placeholder: '请选择' },
      ]
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 160,
          fixed: 'left',
          render: props => {
            return (
              <div>
                <el-button size="mini" disabled={props.row.status == 25631001?false:true} type="text" onClick={() => this.editHandle(props.row,'edit')}>
                  编辑
                </el-button>
                <el-button size="mini" disabled={props.row.status == 25631001?false:true} type="text" onClick={() => this.isSendHandle(props.row,'edit')}>
                  发布
                </el-button>
                <el-button size="mini" disabled={props.row.status == 25631002?false:true} type="text" onClick={() => this.editHandle(props.row,'show')}>
                  查看
                </el-button>
                <el-button size="mini" disabled={props.row.status == 25631001?false:props.row.status == 25631002?false:true} type="text" onClick={() => this.deleteHandle(props.row,'deleteHandle')}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        { title: '发布时间', dataIndex: 'publishDate',dateFormat:'yyyy-MM-dd HH:mm',sorter: true },
        { title: '有效期至', dataIndex: 'endTime', sorter: true ,dateFormat:'yyyy-MM-dd'},
        {
          title: '公告类别',
          dataIndex: 'notificationType',
          sorter: true,
          filter: true,
          filterItems: this.createDictList('2561'),
          render: props => {
            return <span>{this.createDictText(props.row.notificationType, '2561')}</span>;
          }
        },
        { title: '标题', dataIndex: 'notificationTitle', sorter: true },
        {
          title: '紧急程度',
          dataIndex: 'urgency',
          sorter: true,
          filter: true,
          filterItems: this.createDictList('2562'),
          render: props => {
            return <span>{this.createDictText(props.row.urgency, '2562')}</span>;
          }
        },
        { title: '发布人', dataIndex: 'publishPerson', sorter: true },
        {
          title: '状态',
          dataIndex: 'status',
          sorter: true,
          filter: true,
          filterItems: this.createDictList('2563'),
          render: props => {
            return <span>{this.createDictText(props.row.status, '2563')}</span>;
          }
        },
        { title: '已读数量', 
          dataIndex: 'haveread', 
          sorter: true,
          render: props => {
            return <span style="cursor: pointer;display: inline-block;width: 100%;" onClick={() => this.goHaveread(props.row)} >{props.row.haveread}</span>;
          }
         },
        { title: '未读数量', 
          dataIndex: 'notread', 
          sorter: true, 
          render: props => {
            return <span style="cursor: pointer;display: inline-block;width: 100%;" onClick={() => this.goNotread(props.row)} >{props.row.notread}</span>;
          }
        },
      ]
    },
    //搜索获取数据
    changeHandle(val) {
    if(val.publishDate[1]){
           let publishDate1 = Date.parse(val.publishDate[1])
            let d=Date.parse(new Date())
            console.log(publishDate1,d,"searchYear1")
            if(publishDate1 <= d){
                this.fetchParams = Object.assign({},val);
                this.fetchParams.publishDate = val.publishDate[0];
                this.fetchParams.publishDate2 = val.publishDate[1];
                if(val.startTime.length >0){
                    this.fetchParams.startTime = val.startTime[0];
                     this.fetchParams.startTime2 = val.startTime[1];
                }
                console.log('搜索框数据：',this.fetchParams);
            }else{
              this.$message({
                type: 'info',
                message: '发布时间不可大于当前时间!'
              });
            }
      }else{
        this.fetchParams = Object.assign({},val);
        if(val.startTime.length >0){
            this.fetchParams.startTime = val.startTime[0];
            this.fetchParams.startTime2 = val.startTime[1];
        }
      }
      // this.fetchParams = Object.assign({},val);
      // this.fetchParams.publisStartDate = this.fetchParams.publishDate[0];
      // this.fetchParams.publisEndDate = this.fetchParams.publishDate[1];
      // console.log('搜索框数据：',this.fetchParams);
    },
    //展开收起时触发
    collapseHandle() {
    },
    // 新增  编辑 详情
    detailHandle(row,type) {
      this.initData =  {
        type: type,   // add-edit-show
        id:1001
      }; //行id
      this.visibleDrawer = true;
    },
    editHandle(row,type){
      console.log("row:",row);
      this.initData =  {
        type: type,   // add-edit-show
        notificationId: row.notificationId,
        id:1001
      }; //行id
      if(type == 'show'){
        this.title="公告查看"
      }else if(type == 'edit'){
        this.title="公告编辑"
      }
      this.visibleDrawer = true;
    },
    // 发布
    isSendHandle(row,type) {
      // 当天日期
        let currentDate = moment().format('YYYY-MM-DD')
        console.log("currentDate",`${moment(row.endTime).format('YYYY-MM-DD')}`,currentDate)
        if(`${moment(row.endTime).format('YYYY-MM-DD')}` < `${currentDate}`) {
          this.$message({
            message: '发布时有效期不允许是过去时间',
            type: 'info'
          });
        }else{
          this.$confirm('是否继续发布?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            row.isDeleted=0
            publishNotification(row,row.notificationId).then(res=>{
              console.log(res,"res")
              if(res.resultCode == 200){
                  this.$message({
                    type: 'success',
                    message: '发布成功!'
                  });

                  // 重新加载
                this.fetchParams = { ...this.fetchParams };
              }
            })
            
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消发布'
            });          
          });
        }
      },
    // 删除
    deleteHandle(row,type) {
        this.$confirm('是否继续删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteNotification(row.notificationId).then(res=>{
            if(res.resultCode == 200){
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                // 重新加载
                this.fetchParams = { ...this.fetchParams };
            }
          })
          
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
    //关闭详情 rData 是页面关闭回调回来的数据
    infoClose(rData) {
      this.visibleDrawer = false;
      if (rData.type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    // 撤回
    /* async withdraw(){

          this.$confirm('是否撤回', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async() => {
            var ids = this.packageNotificationId(this.rowSelectData);
            var res =  await withdrawNotificationByIds(ids);
            this.validReturnDate(res);
          }).catch(() => {
            this.$notify.info({title: '提示信息',message:'操作取消'});
          });
    }, */
    validReturnDate(res){
      if (res.resultCode === 200) {
        this.$notify.success({title: '提示信息',message:'操作成功!'});
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }else {
        this.$notify.error({title: '提示信息',message:res.errMsg||'操作失败!'});
        
      }
    },
    selectChange(val){
      this.rowSelectData = val;
    },
    packageNotificationId(data){
      var ids = []
      for(var i=0;i<data.length;i++){
          ids.push(data[i].notificationId);
      }
      return ids;
    },
    // 已读
    goHaveread(row){
        console.log(row,"1")
        this.readShow=true
        this.readTitle="已读列表"
        this.readData=row
    },
    // 未读
    goNotread(row){
        console.log(row,"2")
        this.readShow=true
        this.readTitle="未读列表"
        this.readData=row
    },
  }
};
</script>

<style lang="less" scoped>
</style>
